<template>
  <div class="task-info">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>任务信息管理</span>
          <el-button type="primary" @click="handleAdd">新增任务</el-button>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="任务标题">
          <el-input v-model="searchForm.title" placeholder="请输入任务标题" clearable />
        </el-form-item>
        <el-form-item label="订单编号">
          <el-input v-model="searchForm.orderId" placeholder="请输入订单编号" clearable />
        </el-form-item>
        <el-form-item label="优先级" style="width: 210px;">
          <el-select v-model="searchForm.priority" placeholder="请选择优先级" clearable>
            <el-option label="低" value="low" />
            <el-option label="中" value="medium" />
            <el-option label="高" value="high" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" style="width: 210px;">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="待处理" value="待处理" />
            <el-option label="进行中" value="进行中" />
            <el-option label="已完成" value="已完成" />
            <el-option label="已延期" value="已延期" />
          </el-select>
        </el-form-item>
        <el-form-item label="截止日期">
          <el-date-picker
            v-model="searchForm.deadlineRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table
        :data="tableData"
        style="width: 100%"
        v-loading="loading"
        border
        stripe
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="title" label="任务标题" min-width="180" show-overflow-tooltip />
        <el-table-column prop="orderId" label="订单编号" width="120" />
        <el-table-column prop="priority" label="优先级" width="80">
          <template #default="scope">
            <el-tag :type="getPriorityType(scope.row.priority)">
              {{ getPriorityName(scope.row.priority) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusName(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="completionPercentage" label="完成度" width="100">
          <template #default="scope">
            <el-progress :percentage="scope.row.completionPercentage" />
          </template>
        </el-table-column>
        <el-table-column prop="deadline" label="截止日期" width="120">
          <template #default="scope">
            <span :class="{ 'text-danger': isNearDeadline(scope.row.deadline) }">
              {{ scope.row.deadline }}
            </span>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="designerName" label="设计师" width="120" /> -->
        <el-table-column label="操作" fixed="right" width="200">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          :current-page="searchForm.pageNum"
          :page-size="searchForm.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          @update:current-page="val => searchForm.pageNum = val"
          @update:page-size="val => searchForm.pageSize = val"
        />
      </div>

      <!-- 新增/编辑对话框 -->
      <el-dialog
        :title="dialogType === 'add' ? '新增任务' : '编辑任务'"
        v-model="dialogVisible"
        width="600px"
      >
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="100px"
        >
          <el-form-item label="任务标题" prop="title">
            <el-input v-model="form.title" placeholder="请输入任务标题" />
          </el-form-item>
          <el-form-item label="订单编号" prop="orderId">
            <el-input v-model="form.orderId" placeholder="请输入订单编号" />
          </el-form-item>
          <el-form-item label="优先级" prop="priority">
            <el-select v-model="form.priority" placeholder="请选择优先级">
              <el-option label="低" value="low" />
              <el-option label="中" value="medium" />
              <el-option label="高" value="high" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="form.status" placeholder="请选择状态">
              <el-option label="待处理" value="pending" />
              <el-option label="进行中" value="processing" />
              <el-option label="已完成" value="completed" />
              <el-option label="已延期" value="delayed" />
            </el-select>
          </el-form-item>
          <el-form-item label="截止日期" prop="deadline">
            <el-date-picker
              v-model="form.deadline"
              type="date"
              placeholder="请选择截止日期"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item label="完成度" prop="completionPercentage">
            <el-slider
              v-model="form.completionPercentage"
              :step="10"
              show-stops
            />
          </el-form-item>
          <el-form-item label="描述" prop="description">
            <el-input
              v-model="form.description"
              type="textarea"
              :rows="3"
              placeholder="请输入任务描述"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSubmit">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'

// 搜索表单数据
const searchForm = reactive({
  title: '',
  orderId: '',
  priority: '',
  status: '',
  deadlineRange: [],
  pageNum: 1,
  pageSize: 10
})

// 表格数据
const loading = ref(false)
const tableData = ref([])
const total = ref(0)

// 表单数据
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref()
const form = reactive({
  id: null,
  title: '',
  orderId: '',
  priority: 'medium',
  status: 'pending',
  deadline: '',
  completionPercentage: 0,
  description: ''
})

// 表单校验规则
const rules = {
  title: [{ required: true, message: '请输入任务标题', trigger: 'blur' }],
  orderId: [{ required: true, message: '请输入订单编号', trigger: 'blur' }],
  priority: [{ required: true, message: '请选择优先级', trigger: 'change' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
  deadline: [{ required: true, message: '请选择截止日期', trigger: 'change' }],
  completionPercentage: [{ required: true, message: '请设置完成度', trigger: 'change' }]
}

// 获取任务列表
const getTaskList = async () => {
  try {
    loading.value = true
    const params = {
      ...searchForm,
      deadlineStart: searchForm.deadlineRange?.[0],
      deadlineEnd: searchForm.deadlineRange?.[1]
    }
    delete params.deadlineRange
    
    const response = await request.get('/api/designer/task/list', { params })
    tableData.value = response.content
    total.value = response.totalElements
  } catch (error) {
    console.error('获取任务列表失败:', error)
    ElMessage.error('获取任务列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  searchForm.pageNum = 1
  getTaskList()
}

// 重置搜索
const handleReset = () => {
  searchForm.title = ''
  searchForm.orderId = ''
  searchForm.priority = ''
  searchForm.status = ''
  searchForm.deadlineRange = []
  searchForm.pageNum = 1
  getTaskList()
}

// 新增任务
const handleAdd = () => {
  dialogType.value = 'add'
  dialogVisible.value = true
  form.id = null
  form.title = ''
  form.orderId = ''
  form.priority = 'medium'
  form.status = 'pending'
  form.deadline = ''
  form.completionPercentage = 0
  form.description = ''
}

// 编辑任务
const handleEdit = (row) => {
  dialogType.value = 'edit'
  dialogVisible.value = true
  Object.assign(form, row)
}

// 删除任务
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该任务吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await request.delete(`/api/designer/task/${row.id}`)
      ElMessage.success('删除成功')
      getTaskList()
    } catch (error) {
      console.error('删除任务失败:', error)
      ElMessage.error('删除任务失败')
    }
  })
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const data = { ...form }
        // designerId会在请求拦截器中自动添加

        if (dialogType.value === 'add') {
          await request.post('/api/designer/task', data)
          ElMessage.success('新增成功')
        } else {
          await request.put(`/api/designer/task/${form.id}`, data)
          ElMessage.success('更新成功')
        }
        dialogVisible.value = false
        getTaskList()
      } catch (error) {
        console.error('保存任务失败:', error)
        ElMessage.error('保存任务失败')
      }
    }
  })
}

// 分页
const handleSizeChange = (val) => {
  searchForm.pageSize = val
  getTaskList()
}

const handleCurrentChange = (val) => {
  searchForm.pageNum = val
  getTaskList()
}

// 工具方法
const getPriorityName = (priority) => {
  const map = {
    low: '低',
    medium: '中',
    high: '高'
  }
  return map[priority] || priority
}

const getPriorityType = (priority) => {
  const map = {
    low: 'info',
    medium: 'warning',
    high: 'danger'
  }
  return map[priority] || 'info'
}

const getStatusName = (status) => {
  const map = {
    pending: '待处理',
    processing: '进行中',
    completed: '已完成',
    delayed: '已延期'
  }
  return map[status] || status
}

const getStatusType = (status) => {
  const map = {
    pending: 'info',
    processing: 'warning',
    completed: 'success',
    delayed: 'danger'
  }
  return map[status] || 'info'
}

const isNearDeadline = (deadline) => {
  if (!deadline) return false
  const today = new Date()
  const deadlineDate = new Date(deadline)
  const diffDays = Math.ceil((deadlineDate - today) / (1000 * 60 * 60 * 24))
  return diffDays <= 2 && diffDays >= 0
}

// 初始化
onMounted(() => {
  getTaskList()
})
</script>

<style scoped>
.task-info {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.search-form :deep(.el-form-item) {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.text-danger {
  color: #F56C6C;
  font-weight: bold;
}
</style> 